package io.serializable;

import framework.AbstractTest;
import utils.Log;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by shane on 2018/5/28.
 */
public class MyWorld extends AbstractTest {
    private static final String TAG = "MyWorld";

    @Override
    public void test(String[] args) {
        super.test(args);
        try {
            House house = new House();
            List<Animal> animals = new ArrayList<>();
            animals.add(new Animal("Bosco the dog", house));
            animals.add(new Animal("Ralph the hamster", house));
            animals.add(new Animal("Molly the cat", house));

            Log.vn("animals:" + animals.toString());

            ByteArrayOutputStream buf1 = new ByteArrayOutputStream();
            ObjectOutputStream o1 = new ObjectOutputStream(buf1);
            o1.writeObject(animals);
            o1.writeObject(animals);
            o1.close();

            ByteArrayOutputStream buf2 = new ByteArrayOutputStream();
            ObjectOutputStream o2 = new ObjectOutputStream(buf2);
            o2.writeObject(animals);
            o2.close();

            // now get them back
            ObjectInputStream in1 = new ObjectInputStream(new ByteArrayInputStream(buf1.toByteArray()));
            ObjectInputStream in2 = new ObjectInputStream(new ByteArrayInputStream(buf2.toByteArray()));
            List<Animal> a1 = (List<Animal>)in1.readObject();
            List<Animal> a2 = (List<Animal>)in1.readObject();
            List<Animal> a3 = (List<Animal>)in2.readObject();

            Log.vn("animals:" + a1.toString());
            Log.vn("animals:" + a2.toString());
            Log.vn("animals:" + a3.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected String getTag() {
        return TAG;
    }
}

class House implements Serializable {

}

class Animal implements Serializable {
    private String name;

    private House preferredHouse;

    Animal(String name, House h) {
        this.name = name;
        preferredHouse = h;
    }

    @Override
    public String toString() {
        return name + "[" + super.toString() + "]," + preferredHouse + "\n";
    }
}